import AWS from 'aws-sdk'
import * as API from '@/api/bucket'
import store from '@/store'
import { errorCodeMap } from './errorCode'
// import Cookies from 'js-cookie'

export default {
  data() {
    return {
      errorCodeMap,
      baseInfo: {},
      lastTime: null
    }
  },
  computed: {
    stopUploadId() {
      return this.$store.state.app.stopUploadId
    }
  },
  methods: {
    // 文件分片
    fileSlice(file) {
      const size = file.size
      const shardSize = 5 * 1024 * 1024 // 以5MB为一个分片,每个分片的大小
      const shardCount = Math.ceil(size / shardSize) || 1 // 总片数
      const filePartList = []
      for (let i = 0; i < shardCount; i++) {
        const start = i * shardSize
        const end = start + shardSize
        const packet = file.raw.slice(start, end)
        filePartList.push({ PartNumber: i + 1, Body: packet })
      }
      return { filePartList, shardCount }
    },

    // 获取bucket
    async getBucket(baseInfo, expireTime = 360) {
      this.baseInfo = baseInfo
      const ishttps = document.location.protocol === 'https:'
      const params = {
        expireTime,
        bucketName: baseInfo.bucketName
      }
      const { module } = await API.getTempAkSk(params)
      const credentials = {
        accessKeyId: module.accessKey,
        secretAccessKey: module.secretKey
      }
      AWS.config.update(credentials)
      AWS.config.region = baseInfo.region
      AWS.config.endpoint = `${module.domain}/${baseInfo.bucketName}`
      // ?x-image-process=image/resize,p_50
      AWS.config.sslEnabled = ishttps
      AWS.config.s3BucketEndpoint = true
      const bucket = new AWS.S3({ params: { Bucket: baseInfo.bucketName }, signatureVersion: 'v4' })
      this.lastTime = Date.parse(new Date())
      return { bucket, module }
    },

    // 获取上传Id
    getUploadId(params, bucket, file, filePartList, callback) {
      const params1 = {
        Bucket: params.Bucket,
        Key: params.Key
      }
      if (params.editAssets !== 'bucket-inherit') {
        params1.ACL = params.editAssets
      }
      const that = this
      file.bucketName = params.Bucket
      file.region = params.region
      file.prefix = params.prefix
      file.editAssets = params.editAssets
      file.shardCount = params.shardCount
      var req = bucket.createMultipartUpload(params1)
      if (params.module.type === 4) {
        req.on('build', function() {
          req.httpRequest.headers['Iam-roleCrn'] = params.module.roleCrn
          req.httpRequest.headers['X-Amz-Security-Token'] = params.module.securityToken
        })
      }
      if (params.module.type === 3 && params.module.isOpenOrganized && params.module.roleName !== null) {
        req.on('build', function() {
          req.httpRequest.headers['orgrolecrn'] = params.module.roleName
        })
      }
      if (params.editAssets === 'bucket-inherit') {
        req.httpRequest.headers['x-amz-acl'] = 'bucket-inherit'
      }
      req.send(function(err, data) {
        if (err) {
          const code = err.toString().split(':')[0]
          that.$message.error(`${errorCodeMap[code] || '网络错误'}，上传失败`)
          file.status = 'failed'
          file.code = code
          store.commit('app/ADD_UPLOAD_LIST', file)
        } else {
          const UploadId = data.UploadId
          file.UploadId = UploadId
          file.status = 0
          store.commit('app/ADD_UPLOAD_LIST', file)
          const Parts = []
          const index = 0
          const params2 = {
            index,
            shardCount: params.shardCount,
            Parts,
            UploadId,
            Bucket: params.Bucket,
            Key: params.Key,
            uid: file.uid,
            module: params.module
          }
          that.uploadFile(params2, bucket, filePartList, Parts, callback)
        }
      })
    },

    // 上传
    uploadFile(params, bucket, filePartList, Parts, callback) {
      const that = this
      const module = params.module
      const params1 = {
        Body: filePartList[params.index].Body,
        Bucket: params.Bucket,
        Key: params.Key,
        PartNumber: params.index + 1,
        UploadId: params.UploadId
      }
      var req = bucket.uploadPart(params1)
      if (module.type === 4) {
        req.on('build', function() {
          req.httpRequest.headers['Iam-roleCrn'] = module.roleCrn
          req.httpRequest.headers['X-Amz-Security-Token'] = module.securityToken
        })
      }
      if (module.type === 3 && module.isOpenOrganized && module.roleName !== null) {
        req.on('build', function() {
          req.httpRequest.headers['orgrolecrn'] = module.roleName
        })
      }
      req.send(function(err, data) {
        if (err) {
          if (that.stopUploadId.indexOf(params.UploadId) !== -1) {
            const code = '取消上传'
            that.$message.success('取消上传成功')
            store.commit('app/SET_UPLOAD_LIST_Code', { uid: params.uid, code })
            store.commit('app/SET_UPLOAD_LIST', { uid: params.uid, status: 'failed' })
          } else {
            const code = err.toString().split(':')[0]
            that.$message.error(`${errorCodeMap[code] || '网络错误'}，上传失败`)
            store.commit('app/SET_UPLOAD_LIST_Code', { uid: params.uid, code })
            store.commit('app/SET_UPLOAD_LIST', { uid: params.uid, status: 'failed' })
          }
        } else {
          Parts.push({
            ETag: data.ETag,
            PartNumber: params1.PartNumber
          })
          params.index += 1
          const progress = (params.index / params.shardCount).toFixed(2)
          store.commit('app/SET_UPLOAD_LIST', { uid: params.uid, status: progress })
          if (params.index === params.shardCount) {
            const params2 = {
              Bucket: params.Bucket,
              Key: params.Key,
              MultipartUpload: {
                Parts
              },
              UploadId: params.UploadId
            }
            var req = bucket.completeMultipartUpload(params2)
            if (module.type === 4) {
              req.on('build', function() {
                req.httpRequest.headers['Iam-roleCrn'] = module.roleCrn
                req.httpRequest.headers['X-Amz-Security-Token'] = module.type === 4 ? module.securityToken : ''
              })
            }
            if (module.type === 3 && module.isOpenOrganized && module.roleName !== null) {
              req.on('build', function() {
                req.httpRequest.headers['orgrolecrn'] = module.roleName
              })
            }
            req.send(function(err, data) {
              if (err) {
                if (that.stopUploadId.indexOf(params.UploadId) !== -1) {
                  const code = '取消上传'
                  that.$message.success('取消上传成功')
                  store.commit('app/SET_UPLOAD_LIST_Code', { uid: params.uid, code })
                  store.commit('app/SET_UPLOAD_LIST', { uid: params.uid, status: 'failed' })
                } else {
                  const code = err.toString().split(':')[0]
                  that.$message.error(`${errorCodeMap[code] || '网络错误'}，上传失败`)
                  store.commit('app/SET_UPLOAD_LIST_Code', { uid: params.uid, code })
                  store.commit('app/SET_UPLOAD_LIST', { uid: params.uid, status: 'failed' })
                }
              } else {
                store.commit('app/SET_UPLOAD_LIST', { uid: params.uid, status: 'succeeded' })
                that.$message.success('上传成功')
                callback()
              }
            })
          } else {
            const nowTime = Date.parse(new Date())
            if (nowTime - that.lastTime > 5 * 60 * 1000) {
              that.getBucket(that.baseInfo).then(res => {
                that.uploadFile(params, res.bucket, filePartList, Parts, callback)
              })
            } else {
              that.uploadFile(params, bucket, filePartList, Parts, callback)
            }
          }
        }
      })
    },

    // 中止上传
    stopUpload(bucket, params, module) {
      var req = bucket.abortMultipartUpload(params)
      if (module.type === 4) {
        req.on('build', function() {
          req.httpRequest.headers['Iam-roleCrn'] = module.roleCrn
          req.httpRequest.headers['X-Amz-Security-Token'] = module.type === 4 ? module.securityToken : ''
        })
      }
      if (module.type === 3 && module.isOpenOrganized && module.roleName !== null) {
        req.on('build', function() {
          req.httpRequest.headers['orgrolecrn'] = module.roleName
        })
      }
      req.send(function(err, data) {
        if (err) {
          console.log(err)
        } else {
          store.commit('app/SET_STOP_UPLOADID', params.UploadId)
        }
      })
    }
  }
}
